/* CONSTANCE ------------------------------------------------------------------------------------------------------- */
var USERSTORY_RULES = {
    description: {
        required: true,
        minlength: 5,
        maxlength: 10000
    },
    value: {
        required: true,
        range: [0, 1024]
    }
};
var USERSTORY_MESSAGES = {
    description: {
        required: '<span class="text-error">Please enter the description.</span>',
        minlength: '<span class="text-error">The description is too short.</span>',
        maxlength: '<span class="text-error">Please keep the description shorter than 10k characters.</span>'
    },
    value: {
        required: '<span class="text-error">Please enter the business value.</span>',
        range: '<span class="text-error">Business value must between 0 to 1024.</span>'
    }
};
/* end - CONSTANCE ------------------------------------------------------------------------------------------------- */
/* get all projects belong to current logged-in user --------------------------------------------------------------- */
function getProjects() {
    console.log('Loading projects..');

    var $projectSelector = $('.main-selector').find('[name="project"]');

    $.ajax({
        url: GET_PROJECT_CTRL,
        cache: false,
        type: 'post',
        dataType: 'json',
        async: false,
        success: function (data) {
            if (data.result) {
                console.log(data.result.length + ' project(s) loaded successfully!');

                $.each(data.result, function (id, project) {
                    $projectSelector.append('<option value="' + project.id + '">' + project.projectName + '</option>');
                });
            }
        }
    });
}
/* get all projects belong to current logged-in user --------------------------------------------------------------- */

/* get sprints by teamId and projectId ----------------------------------------------------------------------------- */
function getSprints(projectId, teamId) {
    console.log('Loading sprints in Team ' + teamId + '..');

    var $sprintSelector = $('.sprint-selector [name="sprint"]');
    var params = new Object();
    params.projectId = projectId;
    params.teamId = teamId;

    /* clean selector before geting data */
    $sprintSelector.html('');

    $.ajax({
        url: GET_SPRINTS_CTRL,
        cache: false,
        type: 'POST',
        dataType: 'json',
        data: params,
        async: false,
        success: function (data) {
            if (data.result && data.result.length > 0) {
                $sprintSelector.prop('disabled', false);

                $.each(data.result, function (id, sprint) {
                    $sprintSelector.append('<option value="' + sprint.id + '">' + sprint.sprintName + '</option>');

                });
            } else {
                $sprintSelector.append('<option value="">no sprint</option>');
                $sprintSelector.prop('disabled', true);
            }
        }
    });

};
/* end - get sprints by teamId and projectId ----------------------------------------------------------------------- */

/* get team by project id ------------------------------------------------------------------------------------------ */
function getTeams(projectId) {
    console.log('Loading teams in Project ' + projectId + "..");

    var $teamSelector = $('.main-selector [name="team"]');
    var params = new Object();
    params.projectId = projectId;

    /* clean selector before geting data */
    $teamSelector.html('');

    $.ajax({
        url: GET_TEAMS_CTRL,
        cache: false,
        type: 'post',
        dataType: 'json',
        data: params,
        async: false,
        success: function (data) {
            console.log(data.message);
            $teamSelector.prop('disabled', false);
            if (data.result) {
                $.each(data.result, function (id, team) {
                    $teamSelector.append('<option value="' + team.id + '">' + team.teamName + '</option>');
                });
            }
        }
    })
}
/* end - get team by project id ------------------------------------------------------------------------------------ */

/* get user story by project id ------------------------------------------------------------------------------------ */
function getUserStories(projectId) {
    console.log('Loading user stories in Project ' + projectId + "..");

    var params = new Object();
    params.projectId = projectId;
    params.showTodo = $('[name="showTodo"]').val();
    params.showInProgress = $('[name="showInProgress"]').val();
    params.showDone = $('[name="showDone"]').val();

    $('.user-stories').html('');

    $.ajax({
        url: GET_USERSTORY_CTRL,
        cache: false,
        type: 'post',
        dataType: 'json',
        data: params,
        success: function (data) {
            if (data.result) {
                console.log(data.result.length + " user stories loaded.");

                $.each(data.result, function (id, userStory) {
                        var $item = $('.rest-in-peace section.user-story').clone();

                        $item.attr('id', userStory.id);
                        $item.addClass(userStory.status);

                        $item.find('[name="name"]').html(userStory.name);
                        $item.find('[name="description"]').html(userStory.description);
                        $item.find('[name="value"]').html(userStory.value);
                        $item.find('[name="status"]').html(userStory.status);

                        $item.appendTo('.user-stories');
                    }
                );
            }

            $('[name="showTodo"]').click(function () {
                if ($(this).is(':checked')) {
                    $('.to-do').show();
                } else {
                    $('.to-do').hide();
                }
            });
            $('[name="showInProgress"]').click(function () {
                if ($(this).is(':checked')) {
                    $('.in-progress').show();
                } else {
                    $('.in-progress').hide();
                }
            });

            $('[name="showDone"]').click(function () {
                if ($(this).is(':checked')) {
                    $('.done').show();
                } else {
                    $('.done').hide();
                }
            });

            $('.user-story-ctrl').find('.icon-remove').click(function () {
                if (confirm("Delete this user story?")) {
                    var params = new Object();
                    params.userStoryId = $(this).parents('section.user-story').attr('id');
                    $.post(DELETE_USERSTORY_CTRL, params);
                    $(this).parents('section.user-story').hide(300);
                }
            });

            if ($('[name="showTodo"]').is(':checked') == false) {
                $('.to-do').hide();
            }
            if ($('[name="showInProgress"]').is(':checked') == false) {
                $('.in-progress').hide();
            }
            if ($('[name="showDone"]').is(':checked') == false) {
                $('.done').hide();
            }
        }
    });
}
/* end - get user story by project id ------------------------------------------------------------------------------ */


/* set data for user story form ------------------------------------------------------------------------------------ */
function setUserStoryForm(data) {
    var $form = $('.user-story-form');
    $form.find('[name="name"]').val(data.name);
    $form.find('[name="value"]').val(data.value);
    $form.find('[name="status"] option[value="' + data.status + '"]').attr("selected", true);
    $form.find('[name="description"]').val(data.description);
    $form.find('[name="project"]').val(data.project);
}
/* end - set data for user story form ------------------------------------------------------------------------------ */

/* get user story data from Form ----------------------------------------------------------------------------------- */
function getUserStoryFormData() {
    var $form = $('.user-story-form')
    var obj = $form.serializeObject();
    var data = new Object();

    data.id = '';
    data.name = obj.name;
    data.description = obj.description;
    data.value = obj.value;
    data.status = obj.status;
    data.project = obj.project;

    return obj;
}
/* end - get user story data from Form ----------------------------------------------------------------------------- */

/* reset user story form ------------------------------------------------------------------------------------------- */
function resetUserStoryForm() {
    var obj = new Object();
    obj.name = "";
    obj.value = "";
    obj.status = "to-do";
    obj.description = "";
    obj.project = $('.main-selector [name="project"]').val();

    setUserStoryForm(obj);
}
/* end - reset user story form ------------------------------------------------------------------------------------- */

/* create user story ----------------------------------------------------------------------------------------------- */
function createUserStory(data) {
    $.ajax({
        url: CREATE_USERSTORY_CTRL,
        cache: false,
        type: 'POST',
        dataType: 'json',
        data: data,
        success: function () {
            getUserStories($('.main-selector [name="project"]').val());
        }
    });
}
/* end - create user story ----------------------------------------------------------------------------------------- */

/* serialize object ------------------------------------------------------------------------------------------------ */
$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
/* end - serialize object ------------------------------------------------------------------------------------------ */

/* show edit form when edit button clicked ------------------------------------------------------------------------- */
function showEditUserStoryForm(button) {
    var $form = $('.user-story-form');
    var $formParent = $form.parent();
    var $userStory = button.parents('section.user-story');

    // hide create button
    $form.find('[name="create"]').hide();
    // show save button
    $form.find('[name="save"]').show();
    // show status select box
    $form.find('[name="status"]').show();
    // hide current content
    $userStory.find('.content').hide();
    // show the form
    $form.appendTo($userStory);
    $form.fadeIn();

    if ($formParent.is('section.user-story')) {
        // show previous content
        $formParent.find('.content').fadeIn();
    }
}
/* end - show edit form when edit button clicked ------------------------------------------------------------------- */

/* show create form when new button clicked ------------------------------------------------------------------------ */
function showCreateUserStoryForm() {
    var $form = $('.user-story-form');
    var $formParent = $form.parent();
    var projectId = $('.main-selector [name="project"]').val();

    if ($formParent.is('section.user-story')) {
        // show previous content
        $formParent.find('.content').fadeIn();
    }

    if (projectId) {
        // show form on top of user stories
        $form.prependTo('.user-stories');
        // hide save button
        $form.find('[name="save"]').hide();
        // show create button
        $form.find('[name="create"]').show();
        // hide status select box sine default status is to-do
        $form.find('[name="status"]').val('to-do');
        $form.find('[name="status"]').hide();
        // show the form
        $form.show(300);
    }
}
/* end - show create form when new button clicked ------------------------------------------------------------------ */

/* hide user story form when cancel button clicked ----------------------------------------------------------------- */
function hideUserStoryForm() {
    var $form = $('.user-story-form');
    var $formParent = $form.parent();

    if ($formParent.is('section.user-story')) {
        // show previous content
        $formParent.find('.content').fadeIn();
    }

    $form.hide(300);
    setTimeout(function () {
        $form.appendTo('.rest-in-peace');
    }, 300);
}
/* end - hide user story form when cancel button clicked ----------------------------------------------------------- */

/* get data from user story element -------------------------------------------------------------------------------- */
function getDataFromUserStory(userStory) {
    var obj = new Object();
    obj.name = userStory.find('[name="name"]').html();
    obj.description = userStory.find('[name="description"]').html();
    obj.value = userStory.find('[name="value"]').html();
    obj.status = userStory.find('[name="status"]').html();
    obj.project = $('.main-selector [name="project"]').val();

    console.log(obj.status);
    return obj;
}
/* end - get data from user story element -------------------------------------------------------------------------- */

/* save user story to database ------------------------------------------------------------------------------------- */
function saveUserStory(data) {
    $.ajax({
        url: SAVE_USERSTORY_CTRL,
        cache: false,
        type: 'POST',
        dataType: 'json',
        data: data,
        success: function () {
            getUserStories($('.main-selector [name="project"]').val());
        }
    });
}
/* end - save user story to database ------------------------------------------------------------------------------- */